import { ImageAspect, ImageData, ImageDefault, WidgetOption, WidgetStyle, WidgetType } from '@/types'
import WidgetImage from './WidgetImage.vue'
import ImageSetting from './ImageSetting.vue'
import ImageFill from './ImageFill.vue'

export default {
  key: 'image',
  name: '图片',
  type: WidgetType.IMAGE,
  style: WidgetStyle.FILL,
  icon: 'fa-icon-widget-image',
  width: 160,
  height: 120,
  minWidth: 60,
  minHeight: 60,
  resizable: true,
  component: WidgetImage,
  settingComponent: ImageSetting,
  fillingComponent: ImageFill,

  /** 初始控件数据 */
  init(widget, data) {
    const image: ImageData = { ...ImageDefault, ...data.image }

    // 不匹配的比例则不约束
    if (!Object.values(ImageAspect).includes(image.aspect)) {
      image.aspect = ImageAspect.NONE
    }

    widget.image = image
  },

  usingValidate(widget) {
    if (widget.required && !widget.hasFillValue) return `请上传${widget.displayName}`
  },

  clear(widget) {
    Object.assign(widget.image, {
      src: '',
      name: '',
      loading: false,
      progress: 0
    } as ImageData)
  },

  rawWidgetCreator(widgetData, data) {
    const { imageName: name, aspectRatio: aspect } = data

    return Object.assign(widgetData, {
      image: { ...ImageDefault, name, aspect } as ImageData
    })
  },

  rawFieldGetter(widget, data) {
    const { name: imageName, aspect: aspectRatio } = widget.image

    return Object.assign(data, {
      imageName,
      aspectRatio
    })
  }
} as WidgetOption
